class Admin::NewslettersController < Admin::AdministrationController
	
	uses_tiny_mce(:options => {:theme => 'advanced',
		:browsers => %w{msie gecko},
		:theme_advanced_toolbar_location => "top",
		:theme_advanced_toolbar_align => "left",
		:theme_advanced_resizing => true,
		:theme_advanced_resize_horizontal => false,
		:paste_auto_cleanup_on_paste => true,
		:theme_advanced_buttons1 => %w{bold italic underline separator justifyleft justifycenter justifyright indent outdent separator bullist numlist separator link unlink image undo redo},
		:theme_advanced_buttons2 => [],
		:theme_advanced_buttons3 => [],
		:plugins => %w{contextmenu paste}},
	:only => [:new, :edit, :create, :update])	
	
	before_filter :load_newsletter, :only => [ :edit, :update, :destroy, :deliver, :show ]
	
	def new
		@newsletter = Newsletter.new
	end
	
	def create
		@newsletter = Newsletter.new( params[:newsletter] )
		prepare_newsletter
		if @newsletter.save
			flash[:notice] = 'A newsletter foi salva com sucesso'
			render_newsletter
		else
			flash[:error] = 'Existem erros no preenchimento do formulário'
			render :action => 'new'
		end
	end
	
	def edit;  end
	
	def show;  end
	
	def update
		prepare_newsletter
		if @newsletter.update_attributes( params[:newsletter] )
			flash[:notice] = 'A newsletter foi atualizada com sucesso'
			render_newsletter
		else
			flash[:error] = 'Existem erros no preenchimento do formulário'
			render :action => 'edit'      
		end
	end
	
	def deliver
		@newsletter.deliver
		render :action => 'deliver'
	end
	
	def index
		@newsletters = Newsletter.find(:all, :order => 'sent_at desc')
	end
	
	def destroy
		@newsletter.destroy
		flash[:notice] = 'A newsletter foi removida do banco de dados'
		redirect_to :action => 'index'
	end
	
	private
	
	def render_newsletter
		if params[:commit].include?( 'Enviar' )
			deliver
		else
			redirect_to :action => 'show', :id => @newsletter
		end
	end
	
	def prepare_newsletter
		unless params[:groups].blank?
			groups = ContactGroup.find( params[:groups] )
			groups.each do |g|
				g.contacts.each do |c|
					@newsletter << c unless @newsletter.contacts.include?( c )
				end
			end
		end
	end
	
	def load_newsletter
		@newsletter = Newsletter.find(params[:id])
	end
	
end